package com.train.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import java.util.function.Function;

import com.train.common.core.constant.ErrorCodeEnum;
import com.train.common.core.object.*;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.dao.*;
import com.train.webadmin.app.model.*;
import com.train.common.core.base.dao.BaseDaoMapper;
import com.train.common.core.base.service.BaseService;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 考试试卷数据操作服务类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
@Service("tPaperInfoService")
public class TPaperInfoServiceImpl extends BaseService<TPaperInfo, Long> implements TPaperInfoService {

    @Autowired
    private TPaperInfoMapper tPaperInfoMapper;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private TQuestionInfoService tQuestionInfoService;
    @Autowired
    private THistoryPaperService tHistoryPaperService;
    @Autowired
    private TAnswerRecordService tAnswerRecordService;
    @Autowired
    private TPaperQuestService tPaperQuestService;
    @Autowired
    private TPaperQuestMapper tPaperQuestMapper;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TPaperInfo> mapper() {
        return tPaperInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TPaperInfo saveNew(TPaperInfo tPaperInfo) {
        tPaperInfoMapper.insert(this.buildDefaultValue(tPaperInfo));
        return tPaperInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TPaperInfo> tPaperInfoList) {
        if (CollUtil.isNotEmpty(tPaperInfoList)) {
            tPaperInfoList.forEach(this::buildDefaultValue);
            tPaperInfoMapper.insertList(tPaperInfoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<TPaperInfo> tPaperInfoList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(tPaperInfoList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(tPaperInfoList.size(), start + batchSize);
            List<TPaperInfo> subList = tPaperInfoList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<TPaperInfo>, List<TPaperInfo>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    tPaperInfoMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> tPaperInfoMapper.updateById(data));
            } else {
                tPaperInfoList.forEach(this::buildDefaultValue);
                tPaperInfoMapper.insertList(subList);
            }
            if (end == tPaperInfoList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TPaperInfo tPaperInfo, TPaperInfo originalTPaperInfo) {
        tPaperInfo.setCreateUserId(originalTPaperInfo.getCreateUserId());
        tPaperInfo.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        tPaperInfo.setCreateTime(originalTPaperInfo.getCreateTime());
        tPaperInfo.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TPaperInfo> uw = this.createUpdateQueryForNullValue(tPaperInfo, tPaperInfo.getId());
        return tPaperInfoMapper.update(tPaperInfo, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return tPaperInfoMapper.deleteById(id) == 1;
    }

    @Override
    public List<TPaperInfo> getTPaperInfoList(TPaperInfo filter, String orderBy) {
        return tPaperInfoMapper.getTPaperInfoList(filter, orderBy);
    }

    @Override
    public List<TPaperInfo> getTPaperInfoListWithRelation(TPaperInfo filter, String orderBy) {
        List<TPaperInfo> resultList = tPaperInfoMapper.getTPaperInfoList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public List<TPaperInfo> getNotInTPaperInfoListByQuestionId(Long questionId, TPaperInfo filter, String orderBy) {
        List<TPaperInfo> resultList;
        if (questionId != null) {
            resultList = tPaperInfoMapper.getNotInTPaperInfoListByQuestionId(questionId, filter, orderBy);
        } else {
            resultList = getTPaperInfoList(filter, orderBy);
        }
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        return resultList;
    }

    @Override
    public List<TPaperInfo> getTPaperInfoListByQuestionId(Long questionId, TPaperInfo filter, String orderBy) {
        List<TPaperInfo> resultList =
                tPaperInfoMapper.getTPaperInfoListByQuestionId(questionId, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTPaperQuestList(resultList);
        return resultList;
    }

    @Override
    public Map<Long, List<TPaperInfo>> getTPaperInfoListMapByTQuestionInfoList(
            List<TQuestionInfo> tQuestionInfoList, TPaperInfo filter, String orderBy) {
        List<Long> questionIds = tQuestionInfoList.stream().map(TQuestionInfo::getId).collect(Collectors.toList());
        List<TPaperInfo> resultList =
                tPaperInfoMapper.getTPaperInfoListByQuestionIds(questionIds, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTPaperQuestList(resultList);
        return resultList.stream().collect(Collectors.groupingBy(s -> s.getTPaperQuest().getQuestionId()));
    }

    @Override
    public CallResult verifyImportList(List<TPaperInfo> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "classId")) {
            callResult = verifyImportForOneToOneRelation(dataList, "ClassInfo", TPaperInfo::getClassId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "courseId")) {
            callResult = verifyImportForOneToOneRelation(dataList, "CourseInfo", TPaperInfo::getCourseId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    private void buildRelationForTPaperQuestList(List<TPaperInfo> resultList) {
        List<TPaperQuest> tPaperQuestList =
                resultList.stream().map(TPaperInfo::getTPaperQuest).collect(Collectors.toList());
        tPaperQuestService.buildRelationForDataList(tPaperQuestList, MyRelationParam.dictOnly());
    }

    private TPaperInfo buildDefaultValue(TPaperInfo tPaperInfo) {
        TokenData tokenData = TokenData.takeFromRequest();
        tPaperInfo.setCreateUserId(tokenData.getUserId());
        tPaperInfo.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        tPaperInfo.setCreateTime(now);
        tPaperInfo.setUpdateTime(now);
        return tPaperInfo;
    }

    // 判断学生答案是否正确
    private Boolean isRight(TQuestionInfo questionInfo, TAnswerRecord tAnswerRecord) {
        // 将正确答案转换为Set集合
        Set<String> correct = new HashSet<>(Arrays.asList(questionInfo.getCorrectAnswer().split("&")));
        // 将学生答案转换为Set集合
        Set<String> userResp = new HashSet<>(Arrays.asList(tAnswerRecord.getUserAnswer().split("&")));

        // 判断学生答案是否包含所有正确答案，并且正确答案是否包含所有学生答案
        return correct.containsAll(userResp) && userResp.containsAll(correct);
    }

    public List<TPaperInfo> listPaperByClassId(Long classId) {
        return tPaperInfoMapper.listPaperByClassId(classId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void chooseQuestion(Long paperId, Long[] questionIds) {
        tPaperQuestMapper.deleteByPaperId(paperId);
        List<TPaperQuest> tPaperQuestList = new ArrayList<>();
        for (Long questionId : questionIds) {
            TPaperQuest tPaperQuest = new TPaperQuest();
            tPaperQuest.setPaperId(paperId);
            tPaperQuest.setQuestionId(questionId);
            tPaperQuestList.add(tPaperQuest);
        }
        tPaperQuestService.saveNewBatch(tPaperQuestList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Double submitPaper(List<TAnswerRecord> answerRecords, TPaperInfo paperInfo, THistoryPaper tHistoryPaper) {
        //获取用户id
        TokenData tokenData = TokenData.takeFromRequest();
        StudentInfo studentInfo = studentInfoService.getStudentInfoByUserId(tokenData.getUserId());
        THistoryPaper paper = new THistoryPaper();
        paper.setStudentId(studentInfo.getId());
        paper.setPaperId(paperInfo.getId());
        if (tHistoryPaperService.getTHistoryPaperList(paper, "").size() > 0) {
            throw new RuntimeException("试卷已提交,请勿重复提交");
        }

        // 保存历史试卷记录
        tHistoryPaper.setStudentId(studentInfo.getId());
        tHistoryPaper.setPaperId(paperInfo.getId());
        tHistoryPaperService.saveNew(tHistoryPaper);

        // 获取试卷所有题目
        List<TQuestionInfo> questionInfos = tQuestionInfoService.getQuestionInfoByPaperId(paperInfo.getId());
        if (questionInfos.isEmpty()) {
            throw new RuntimeException("试卷无题目信息");
        }

        // 题目映射表：questionId -> TQuestionInfo
        Map<Long, TQuestionInfo> questionMap = questionInfos.stream()
                .collect(Collectors.toMap(TQuestionInfo::getId, Function.identity()));

        // 校验提交的答案是否属于该试卷
        for (TAnswerRecord answer : answerRecords) {
            if (!questionMap.containsKey(answer.getQuestionId())) {
                throw new RuntimeException("存在无效题目ID: " + answer.getQuestionId());
            }
        }

        // 答案映射表：questionId -> TAnswerRecord（学生提交的）
        Map<Long, TAnswerRecord> answerMap = answerRecords.stream()
                .collect(Collectors.toMap(TAnswerRecord::getQuestionId, Function.identity()));

        List<TAnswerRecord> allAnswers = new ArrayList<>();
        double totalScore = 0.0;

        // 遍历所有题目，生成完整答案记录
        for (TQuestionInfo question : questionInfos) {
            Long qid = question.getId();
            TAnswerRecord answer = answerMap.get(qid);
            if (answer == null) {
                // 未作答题目，创建默认记录（0分）
                answer = new TAnswerRecord();
                answer.setQuestionId(qid);
                answer.setUserAnswer("");
                answer.setIsCorrect(0);
                answer.setScore(0.0);
            } else {
                // 判题逻辑：根据正确答案计算得分
                boolean isCorrect = isRight(question, answer);
                answer.setIsCorrect(isCorrect ? 1 : 0);
                answer.setScore(isCorrect ? question.getScore() : 0.0);
                totalScore += answer.getScore();
            }
            answer.setHistoryPaperId(tHistoryPaper.getId());
            allAnswers.add(answer);
        }

        // 批量保存答案记录
        tAnswerRecordService.saveBatch(allAnswers);

        // 更新历史记录总分
        tHistoryPaper.setScore(totalScore);
        tHistoryPaperService.updateById(tHistoryPaper);

        return totalScore;
    }

    public List<TPaperInfo> getStudentTPaperInfoList() {
        TokenData tokenData = TokenData.takeFromRequest();
        StudentInfo studentInfo = studentInfoService.getStudentInfoByUserId(tokenData.getUserId());
        return tPaperInfoMapper.getStudentTPaperInfoList(studentInfo.getId());
    }
}
